import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:htxd_flutter_mapbox_sdk/htxd_flutter_mapbox_sdk.dart';
import 'package:mapbox_maps_flutter/mapbox_maps_flutter.dart';

import '../mapview/base_map_view.dart';

/// 地图加载 失败
typedef MapLoadFailed = Function(String message);

/// 地图加载 成功
typedef MapLoadSuccess = Function(DrawLandManager drawLandManager);

/// 地块开始移动
typedef OnLandStartMove = Function();

/// 地块移动过程中
typedef OnLandMoving = Function();

/// 地块移动结束
typedef OnLandMoveEnd = Function();

/// 开始勾画 操作
typedef OnLandStartDraw = Function();

/// 添加点 操作
typedef OnLandAddPoint = Function();

/// 撤销操作
typedef OnLandUndo = Function();

/// 删除操作
typedef OnLandDelete = Function();

/// 完成操作
typedef OnLandComplete = Function();

/// 地图移动操作
typedef OnMapMove = Function();

/// BaseDrawMapView
class BaseDrawMapView extends StatefulWidget {
  /// 地图加载失败
  final MapLoadFailed? mapLoadFailed;

  /// 地图加载成功
  final MapLoadSuccess? mapLoadSuccess;

  /// 地图长按操作
  final OnMapLongTapListener? onMapLongTapListener;

  /// 地图点击操作
  final OnMapTapListener? onMapTapListener;

  /// 地图移动操作
  final OnMapScrollListener? onMapScrollListener;

  /// 开始移动
  final OnLandStartMove? onLandStartMove;

  /// 移动过程中
  final OnLandMoving? onLandMoving;

  /// 移动结束
  final OnLandMoveEnd? onLandMoveEnd;

  /// 开始勾画
  final OnLandStartDraw? onLandStartDraw;

  /// 添加点
  final OnLandAddPoint? onLandAddPoint;

  /// 撤销
  final OnLandUndo? onLandUndo;

  /// 删除
  final OnLandDelete? onLandDelete;

  /// 完成
  final OnLandComplete? onLandComplete;

  /// 地图移动
  final OnMapMove? onMapMove;

  bool isStartLocation = false;

  BaseDrawMapView(
      {Key? key,
      this.isStartLocation = false,
      this.mapLoadSuccess,
      this.mapLoadFailed,
      this.onMapTapListener,
      this.onMapLongTapListener,
      this.onMapScrollListener,
      this.onLandStartMove,
      this.onLandMoving,
      this.onLandMoveEnd,
      this.onLandStartDraw,
      this.onLandAddPoint,
      this.onLandUndo,
      this.onLandDelete,
      this.onLandComplete,
      this.onMapMove})
      : super(key: key);

  @override
  State<BaseDrawMapView> createState() => _BaseDrawMapViewState();
}

class _BaseDrawMapViewState extends State<BaseDrawMapView> {
  MapBoxControl? _control;
  MapBoxControl? _mirrorControl;
  DrawLandManager? _drawLandManager;
  bool _isMove = false;
  DrawType? _drawType;
  int? _selectPosition;
  List<ScreenCoordinate>? _position;
  MoveType? _moveType;
  Offset? _moveOffset;
  Position? _startMoveCenter;

  int lastTime = 0;

  int lastZoom = 17;

  @override
  void initState() {
    super.initState();
    DrawLandWebSocketListener.addListener((message) {
      if (message['type'] == "block") {
        var p = message['points'];
        if (p is List) {
          List<Position> pos = p
              .map((e) => Position(double.tryParse("${e['longitude']}") ?? 0,
                  double.tryParse("${e['latitude']}") ?? 0))
              .toList();
          print("一共：${pos.length}个点,开始重绘");
          _drawLandManager?.drawLand?.posi.clear();
          _drawLandManager?.drawLand?.posi.addAll(pos);
          _drawLandManager?.drawLand?.draw();
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Listener(
          onPointerDown: (event) {
            _drawLandManager?.downEvent(event);
          },
          onPointerMove: (event) {
            _drawLandManager?.moveEvent(event);
          },
          onPointerUp: (event) {
            _drawLandManager?.upEvent(event);
          },
          child: BaseMapView(
            isStartLocation: widget.isStartLocation,
            mapLoadSuccess: (control) {
              // 地图加载成功
              _control = control;
              _drawLandManager = DrawLandManager(_control!,
                  landStartMove: _landStartMove,
                  landMoving: _landMoving,
                  landMoveEnd: _landMoveEnd,
                  onLandStartDraw: widget.onLandStartDraw,
                  onLandAddPoint: widget.onLandAddPoint,
                  onLandUndo: widget.onLandUndo,
                  onLandDelete: widget.onLandDelete,
                  onLandComplete: widget.onLandComplete,
                  onMapTapListener: widget.onMapTapListener);
              if (widget.mapLoadSuccess != null) {
                widget.mapLoadSuccess!(_drawLandManager!);
              }
            },
            mapLoadFailed: (message) {
              // 地图加载失败
              if (widget.mapLoadFailed != null) {
                widget.mapLoadFailed!(message);
              }
            },
            onMapTapListener: (coordinate) {
              // 地图点击事件
              Position position = Position(coordinate.y, coordinate.x);
              _drawLandManager?.mapClickEvent(position);
            },
            onMapLongTapListener: (coordinate) {
              // 地图长按
              if (widget.onMapLongTapListener != null) {
                widget.onMapLongTapListener!(coordinate);
              }
            },
            onMapScrollListener: (coordinate) {
              // 地图移动
              if (widget.onMapScrollListener != null) {
                widget.onMapScrollListener!(coordinate);
              }
              int now = DateTime.now().millisecondsSinceEpoch;
              if ((lastTime - now).abs() > 500) {
                DrawLandWebSocketListener.endMove(coordinate);
              }
              lastTime = now;
            },
            onCameraChangeListener: (cameraChangedEventData) async {
              widget.onMapMove?.call();
              double? originzoom =
                  (await _control?.mapboxMap.getCameraState())?.zoom;
              if (originzoom == null) return;
              int zoom = originzoom.toInt();
              if (zoom != lastZoom) {
                DrawLandWebSocketListener.scaleChange(zoom);
                lastZoom = zoom;
              }
            },
          ),
        ),
        _isMove
            ? LandWidget(
                drawType: _drawType,
                selectPosition: _selectPosition,
                position: _position,
                moveType: _moveType,
                moveOffset: _moveOffset,
              )
            : const SizedBox(),
        Align(
          alignment: Alignment.topLeft,
          child: Container(
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(5.w)),
                border: Border.all(color: Colors.white, width: 2.w)),
            margin: EdgeInsets.only(
              right: _isMove ? 0 : ScreenUtil().screenWidth * 5,
              top: _isMove ? 0 : ScreenUtil().screenHeight * 5,
            ),
            width: 200.w,
            height: 200.w,
            child: Stack(
              children: [
                BaseMapView(
                  mapLoadSuccess: (control) {
                    _mirrorControl = control;
                    _drawLandManager?.mirrorControl = _mirrorControl!;

                    if (_isMove && _moveType == MoveType.START_MOVE) {
                      if (_startMoveCenter != null) {
                        _mirrorMapFlyToCenter(
                            Point(coordinates: _startMoveCenter!));
                      }
                    }
                    Future.delayed(const Duration(milliseconds: 100))
                        .then((value) {
                      _mirrorControl!.showTypeLayer(_control!.showType);
                    });
                  },
                ),
                MirrorLandWidget(
                  drawType: _drawType,
                  selectPosition: _selectPosition,
                  position: _position,
                  moveType: _moveType,
                  moveOffset: _moveOffset,
                )
              ],
            ),
          ),
        )
      ],
    );
  }

  // 地块开始移动
  void _landStartMove(
      DrawType drawType, int selectPosition, List<Position> positions) async {
    if (_control == null) {
      return;
    }
    List<ScreenCoordinate> coordinates = [];
    for (var value in positions) {
      coordinates.add(await _control!.positionToScreen(value));
    }
    _startMoveCenter = positions[selectPosition - 1];
    await _mirrorMapFlyToCenter(Point(coordinates: _startMoveCenter!));
    setState(() {
      _drawType = drawType;
      _position = coordinates;
      _selectPosition = selectPosition;
      _moveType = MoveType.START_MOVE;
      _isMove = true;
    });
    if (widget.onLandStartMove != null) {
      widget.onLandStartMove!();
    }
  }

  Future<void> _mirrorMapFlyToCenter(Point point) async {
    var cameraState = await _control?.mapboxMap.getCameraState();
    await _mirrorControl?.mapboxMap.flyTo(
        CameraOptions(
          center: point.toJson(),
          padding: cameraState?.padding,
          zoom: cameraState?.zoom,
          bearing: cameraState?.bearing,
          pitch: cameraState?.pitch,
        ),
        MapAnimationOptions(duration: 0, startDelay: 0));
  }

  // 地块移动过程中
  Future<void> _landMoving(Offset offset) async {
    var position = await _control?.screenToPosition(ScreenCoordinate(
        x: offset.dx * MyScreenUtil.pixelRatio,
        y: offset.dy * MyScreenUtil.pixelRatio));
    await _mirrorMapFlyToCenter(Point(coordinates: position!));
    setState(() {
      _moveOffset = offset;
      _moveType = MoveType.MOVING;
    });
    if (widget.onLandMoving != null) {
      widget.onLandMoving!();
    }
  }

  // 地块移动结束
  void _landMoveEnd() {
    setState(() {
      _isMove = false;
      _moveType = MoveType.END_MOVE;
    });
    if (widget.onLandMoveEnd != null) {
      widget.onLandMoveEnd!();
    }
  }
}
